import { ref, onMounted, nextTick, computed } from 'vue';
import { useMenuStore } from '@/stores/menu-store';
import { Panel } from '@jecloud/ui';
import { useProvideSiderMenu } from '../context';
import Sortable from 'sortablejs';
import { createElement, hasClass, debounce, split } from '@jecloud/utils';
import { useUserConfigStore } from '@/stores/user-config-store';

export function useSiderMenu() {
  const menuStore = useMenuStore();
  const userConfigStore = useUserConfigStore();
  const siderEl = ref();
  const tabsEl = ref();
  const tabsCodes = ref(split(userConfigStore.siderMenuSort || 'menus,star,history', ','));
  const tabs = computed(() => {
    return tabsCodes.value.map((code) => {
      return tabsData[code];
    });
  });
  const panelContext = Panel.useInjectPanel();
  const panelItem = panelContext.getPanelItem('left');
  menuStore.initMenuActiveTab();
  const activeTab = computed(
    () => tabs.value.find((tab) => tab.code === menuStore.activeSiderTab) || tabs.value[0],
  );
  const pin = ref(true);
  const isHover = ref(false);

  // 锁定
  const clickPin = () => {
    pin.value = !pin.value;
    panelItem.setExpand(pin.value);
  };
  // 切换
  const clickTab = (tab) => {
    menuStore.setMenuActiveTab(tab.code);
  };

  // 父对象
  useProvideSiderMenu({
    collapsed: panelItem.collapsed,
    isHover,
  });

  // tab排序
  onMounted(() => {
    nextTick(() => {
      const el = createElement(siderEl.value);
      const setHover = debounce((hover) => {
        isHover.value = hover;
      }, 200);
      el.on('mouseenter', () => {
        setHover(true);
      });
      el.on('mouseleave', () => {
        setHover(false);
      });

      Sortable.create(tabsEl.value, {
        handle: '.sider-menu-toolbar-item',
        forceFallback: true,
        ghostClass: 'sider-menu-toolbar-item-sortable-ghost',
        preventOnFilter: false,
        delay: 50,
        filter(evt, item) {
          return !hasClass(item, 'is--draggable');
        },
        onEnd: ({ oldIndex, newIndex }) => {
          const tab = tabsCodes.value.splice(oldIndex, 1)[0];
          tabsCodes.value.splice(newIndex, 0, tab);
          userConfigStore.setSiderMenuSort(tabsCodes.value.join(','));
        },
      });
    });
  });

  return {
    tabs,
    tabsEl,
    siderEl,
    pin,
    activeTab,
    panelItem,
    isHover,
    clickTab,
    clickPin,
  };
}
/**
 * 菜单tab数据
 */
const tabsData = {
  menus: {
    code: 'menus',
    component: 'AdminSiderMenus',
    icon: 'jeicon jeicon-work',
    selectedIcon: 'jeicon jeicon-work-on',
  },
  star: {
    code: 'star',
    component: 'AdminSiderMenuStar',
    icon: 'fal fa-star',
    selectedIcon: 'fas fa-star',
  },
  history: {
    code: 'history',
    component: 'AdminSiderMenuHistory',
    icon: 'fal fa-clock',
    selectedIcon: 'fas fa-clock',
  },
};
